//
//  NSFileTableView.m
//  Penda
//
//  Created by Duckjin Kang on 1/4/10.
//  Copyright 2010 StonyBrookUniv.. All rights reserved.
//

#import "NSFileTableView.h"
#import "NSFileInfoItem.h"


@implementation NSFileTableView

- (void)awakeFromNib {
	files = [[NSMutableArray alloc] init];
	[self registerForDraggedTypes:[NSArray arrayWithObjects:NSFilenamesPboardType, nil]];
}

- (void) acceptFilenameDrag:(NSString *) filename
{
	NSArray* pAll = [arrayController arrangedObjects];
	NSFileInfoItem *newItem = [[NSFileInfoItem alloc] initWithFilePath:filename];
	if ([pAll indexOfObject:newItem] == NSNotFound)
		[arrayController addObject:newItem];
	else 
		[newItem release];
}

- (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender
{
	if ([[[sender draggingPasteboard] types] containsObject:NSFilenamesPboardType])
	{
		return NSDragOperationCopy;
	}
	
	return NSDragOperationNone;
}

// Stop the NSTableView implementation getting in the way
- (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)sender
{
	return [self draggingEntered:sender];
}

- (BOOL)performDragOperation:(id <NSDraggingInfo>)sender
{
	int i;
	NSPasteboard *pboard;
	pboard = [sender draggingPasteboard];
	if ([[pboard types] containsObject:NSFilenamesPboardType])
	{
		NSArray *filenames = [pboard propertyListForType:NSFilenamesPboardType];
		{
			for (i=0;i<[filenames count];i++)
			{
				[self acceptFilenameDrag:[filenames objectAtIndex:i]];
			}
		}
		return YES;
	}
	return NO;
}	

-(IBAction) onAddFileDlg:(id)sender {
	NSOpenPanel *pop = [NSOpenPanel openPanel];
	[pop setAllowsMultipleSelection:YES];
	[pop setCanChooseDirectories:YES];
	[pop runModal];
	for (int i=0;i<[[pop URLs] count];i++) {
		[self acceptFilenameDrag:[ [[pop URLs] objectAtIndex:i] path] ];
	}
}
-(IBAction) onFlushSelected:(id)sender {
	NSArray* pSelected = [arrayController selectedObjects];
	for (int i=0;i<[pSelected count];i++) {
		[[pSelected objectAtIndex:i] flush];
		
	}
}

-(IBAction) onFlushAll:(id)sender {
	for (int i=0;i<[[arrayController arrangedObjects] count];i++) {
		[[[arrayController arrangedObjects] objectAtIndex:i] flush];
		
	}
}

@end
